package com.fqgj.xjd.user.service.impl;

import com.fqgj.common.api.Response;
import com.fqgj.xjd.user.client.UserOcrInfoService;
import com.fqgj.xjd.user.client.enums.UserOcrTypeEnum;
import com.fqgj.xjd.user.client.request.UserOcrInfo;
import com.fqgj.xjd.user.dao.UserOcrInfoDao;
import com.fqgj.xjd.user.entity.UserOcrInfoEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author moss
 * 2019-05-29
 */
@Service("userOcrInfoService")
public class UserOcrInfoServiceImpl implements UserOcrInfoService {

    @Autowired
    UserOcrInfoDao userOcrInfoDao;

    @Override
    public Response saveUserOcrInfo(UserOcrInfo userOcrInfo) {
        Assert.notNull(userOcrInfo, "[userOcrInfo] must not be null");
        Assert.notNull(userOcrInfo.getOcrType(), "[userOcrInfo] must not be null");
        UserOcrInfoEntity userOcrInfoEntity = new UserOcrInfoEntity();
        BeanUtils.copyProperties(userOcrInfo, userOcrInfoEntity);
        userOcrInfoEntity.setOcrType(userOcrInfo.getOcrType().name())
                .setProviderType(userOcrInfo.getProviderType());
        userOcrInfoDao.insert(userOcrInfoEntity);
        return Response.ok();
    }

    @Override
    public Response<UserOcrInfo> getByUserCodeAndType(UserOcrInfo userOcrInfo) {
        Assert.notNull(userOcrInfo, "[userOcrInfo] must not be null");
        Assert.notNull(userOcrInfo.getOcrType(), "[userOcrInfo] must not be null");
        Assert.notNull(userOcrInfo.getUserCode(), "[userOcrInfo] must not be null");
        Map<String, Object> map = new HashMap<>();
        map.put("userCode", userOcrInfo.getUserCode());
        map.put("ocrType", userOcrInfo.getOcrType().name());
        List<UserOcrInfoEntity> userOcrInfoEntities = userOcrInfoDao.selectByParams(map);
        if (CollectionUtils.isEmpty(userOcrInfoEntities)) {
            return Response.ok().putData(null);
        }

        UserOcrInfoEntity userOcrInfoEntity = userOcrInfoEntities.get(userOcrInfoEntities.size() - 1);
        userOcrInfo.setOcrResultUrl(userOcrInfoEntity.getOcrResultUrl());
        return Response.ok().putData(userOcrInfo);
    }
}
